package cn.wolfcode.job;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.redis.JobRedisKey;
import cn.wolfcode.web.fegin.SeckillProductFeginApi;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Getter
@Setter
public class SeckillProductCacheJob implements SimpleJob {
    @Autowired
    private SeckillProductFeginApi seckillProductFeginApi;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${jobCron.SeckillProductCache}")
    private String cron;
    @Override
    public void execute(ShardingContext shardingContext) {
        String time = shardingContext.getShardingParameter();
        //根据当天秒杀场次time查询该场次的秒杀数据
        Result<List<SeckillProductVo>> listResult = seckillProductFeginApi.queryByTimeForJob(Integer.parseInt(time));
        if (listResult == null && listResult.hasError()){
            System.out.println("系统繁忙，请稍后再试，谢谢！");
            return;
        }
        List<SeckillProductVo> data = listResult.getData();
        //放入缓存中，key == seckill_product_hash：10
        String redisKey = JobRedisKey.SECKILL_PRODUCT_HASH.getRealKey(time);
        //将秒杀库存数放入Redis中
        String stockCountKey = JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time);
        redisTemplate.delete(redisKey);
        redisTemplate.delete(stockCountKey);
        for (SeckillProductVo vo : data) {
             /*存入Redis 中
             key: seckill_product_hash：time
             value(key:seckillId,value：vo对象)*/
            redisTemplate.opsForHash().put(redisKey,String.valueOf(vo.getId()), JSON.toJSONString(vo));
            //库存数
            redisTemplate.opsForHash().put(stockCountKey,String.valueOf(vo.getId()),String.valueOf(vo.getStockCount()));
        }
        System.out.println("执行完毕");
    }
}
